package test.wordprj.word.uitl;

import test.wordprj.word.bean.MenuExcelModel;
import test.wordprj.word.bean.MenuNode;

import java.util.ArrayList;
import java.util.List;

public class TreeDataFlatter {
    public static List<MenuExcelModel> convert(List<MenuNode> treeData) {
        List<MenuExcelModel> result = new ArrayList<>();
        for (MenuNode node : treeData) {
            MenuExcelModel models = new MenuExcelModel();
            handleFirstNode(node, result, models, 0);
        }
        return result;
    }

    private static void flattenNode(MenuNode node, List<MenuExcelModel> result, String[] levels, int depth) {
        if (depth >= 5) return; // 最大支持五级

        levels[depth] = node.getName();

        // 当前节点作为一行数据
        MenuExcelModel model = new MenuExcelModel();
        switch (depth) {
            case 0: model.setLevel1(levels[0]); break;
            case 1: model.setLevel2(levels[1]); break;
            case 2: model.setLevel3(levels[2]); break;
            case 3: model.setLevel4(levels[3]); break;
            case 4: model.setLevel5(levels[4]); break;
        }
        if (node.getChildren() != null && !node.getChildren().isEmpty()) {
            handleFirstNode(node.getChildren().get(0), result, model, 1);
        }
        //result.add(model);

        // 递归处理子节点
      /*  if (node.getChildren() != null && !node.getChildren().isEmpty()) {
            for (MenuNode child : node.getChildren()) {
                // 复制父级层级信息
                String[] childLevels = Arrays.copyOf(levels, 5);
                flattenNode(child, result, childLevels, depth + 1);
            }
        }*/
    }

    private static void handleFirstNode (MenuNode node,List<MenuExcelModel> result , MenuExcelModel model, int depth) {
        String name = node.getName();
        switch (depth) {
            case 0: model.setLevel1(name); break;
            case 1: model.setLevel2(name); break;
            case 2: model.setLevel3(name); break;
            case 3: model.setLevel4(name); break;
            case 4: model.setLevel5(name); break;
        }
        if (node.getChildren() == null || node.getChildren().isEmpty()) {
            result.add(model);
            return;
        }
         handleFirstNode(node.getChildren().get(0),result, model, depth + 1);
        if (node.getChildren().size() > 1) {
            for (int i = 1; i < node.getChildren().size(); i++) {
                MenuExcelModel models = new MenuExcelModel();
                handleFirstNode(node.getChildren().get(i), result, models, depth + 1);
            }
        }

    }
}
